'use client'
import React, { useState, useEffect, useCallback, useRef } from 'react';
import { Search, Menu, BookOpen, X, User, LogOut } from 'lucide-react';
import { Input } from './ui/input';
import { Button } from './ui/button';
import Link from 'next/link';
import LoginRegisterModal from './LoginRegisterModal';
import { getCategories } from '../services/categoryService';
import { Category } from '@/types/category';
import { toast } from 'sonner';
import { useRouter } from 'next/router';


interface HeaderProps {
  onSearch: (query: string) => void;
  onCategoryChange: (category: Category | null) => void;
  currentCategory: Category | null;
}

// 使用useEffect确保只在客户端执行CSS动画定义
export default function Header({ onSearch, onCategoryChange, currentCategory }: HeaderProps) {
  const [isLoggedIn, setIsLoggedIn] = useState(false);
  const [userEmail, setUserEmail] = useState('');
  const [userAvatar, setUserAvatar] = useState('');
  const [isDropdownOpen, setIsDropdownOpen] = useState(false);
  const dropdownRef = useRef<HTMLDivElement>(null);
  
  // 添加CSS动画定义（仅在客户端执行）
  useEffect(() => {
    // 确保在客户端环境
    if (typeof document !== 'undefined') {
      const styleSheet = document.createElement("style");
      styleSheet.textContent = `
        @keyframes bounceIn {
          0% {
            transform: scale(0.8) translateY(-10px);
            opacity: 0;
          }
          40% {
            transform: scale(1.02) translateY(12px);
          }
          70% {
            transform: scale(1.05) translateY(6px);
          }
          85% {
            transform: scale(0.98) translateY(-3px);
          }
          100% {
            transform: scale(1) translateY(0);
            opacity: 1;
          }
        }
        
        .menu-item-hover {
          transition: all 0.2s ease;
        }
        
        .menu-item-hover:hover {
          transform: translateX(4px);
        }
      `;
      document.head.appendChild(styleSheet);
      
      // 清理函数
      return () => {
        document.head.removeChild(styleSheet);
      };
    }
  }, []);
  const [categories, setCategories] = useState<Category[]>([]);
  const [isComposing, setIsComposing] = useState(false);
  const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false);
  const [searchInput, setSearchInput] = useState('');
  const menuRef = React.useRef<HTMLDivElement>(null);
  const menuButtonRef = React.useRef<HTMLButtonElement>(null);

  // 点击菜单外部自动关闭
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (isMobileMenuOpen && 
          menuRef.current && !menuRef.current.contains(event.target as Node) &&
          menuButtonRef.current && !menuButtonRef.current.contains(event.target as Node)) {
        setIsMobileMenuOpen(false);
      }
    };

    document.addEventListener('mousedown', handleClickOutside);
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, [isMobileMenuOpen]);

  // 检查登录状态
  useEffect(() => {
    const token = localStorage.getItem('auth_token');
    const userInfo = localStorage.getItem('user');
    if (token && userInfo) {
      setIsLoggedIn(true);
      try {
        const userData = JSON.parse(userInfo);
        setUserEmail(userData.username || '');
        setUserAvatar(userData.avatar || `https://ui-avatars.com/api/?name=${encodeURIComponent(userData.email?.split('@')[0] || 'User')}&background=random`);
      } catch (e) {
        console.error('解析用户信息失败', e);
      }
    }
  }, []);

  // 处理登录成功
  const handleLoginSuccess = () => {
    setIsLoggedIn(true);
    // 刷新用户信息
    const userInfo = localStorage.getItem('user');
    if (userInfo) {
      try {
        const userData = JSON.parse(userInfo);
        setUserEmail(userData.email || '');
        setUserAvatar(userData.avatar || `https://ui-avatars.com/api/?name=${encodeURIComponent(userData.email?.split('@')[0] || 'User')}&background=random`);
      } catch (e) {
        console.error('解析用户信息失败', e);
      }
    }
  };

  // 处理个人中心点击
  const handleProfileClick = () => {
    setIsDropdownOpen(false);
    // 这里可以添加跳转到个人中心页面的逻辑
    toast.success('跳转到个人中心');
    // 跳转到个人中心页面
    //window.location.href = '/profile';

  };

  // 点击下拉菜单外部自动关闭
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (isDropdownOpen && 
          dropdownRef.current && 
          !dropdownRef.current.contains(event.target as Node)) {
        setIsDropdownOpen(false);
      }
    };

    document.addEventListener('mousedown', handleClickOutside);
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, [isDropdownOpen]);

  // 处理登出
  const handleLogout = () => {
    localStorage.removeItem('auth_token');
    localStorage.removeItem('user');
    setIsLoggedIn(false);
    setUserEmail('');
  };

  // categories 状态已在组件顶部定义

  // 获取分类数据
  useEffect(() => {
    const loadCategories = async () => {
      try {
        // 先尝试从localStorage获取分类
        const item = localStorage.getItem('categories');
        if(!item){
          const fetchedCategories: Category[] = await getCategories();
          //存入本地缓存
          localStorage.setItem('categories', JSON.stringify(fetchedCategories));
        }

        const fetchedCategories: Category[] = await getCategories();
        //存入本地缓存
        localStorage.setItem('categories', JSON.stringify(fetchedCategories));

        console.log('获取到的分类:', fetchedCategories);
        if (Array.isArray(fetchedCategories) && fetchedCategories.length > 0 ) {
        setCategories(fetchedCategories);
        // 保持初始的null状态，显示"全部"文章
        // 不自动设置默认分类，让用户自己选择
      }
        
      } catch (error) {
        console.error('加载分类失败:', error);
        // 保留默认分类，确保界面正常显示
        // setCategories(['全部', '技术', '生活', '旅行', '美食', '设计']);
      }
    };

    loadCategories();
  }, []);



  return (
    <header className="sticky top-0 bg-white border-b border-gray-200 z-50">
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div className="flex items-center justify-between h-16">
          <Link href="/" className="flex items-center gap-2 cursor-pointer hover:text-blue-700 transition-colors">
            <BookOpen className="w-8 h-8 text-blue-600" />
            <span className="text-blue-600 font-medium">博客空间</span>
          </Link>
          
          <nav className="hidden md:flex items-center gap-6">
            {/* 添加"全部"选项，用于显示所有分类的文章 */}
            <button
              onClick={() => onCategoryChange(null)}
              className={`transition-colors ${
                currentCategory === null
                  ? 'text-blue-600'
                  : 'text-gray-600 hover:text-blue-600'
              }`}
            >
              全部
            </button>
            {categories.map((item) => (
              <button
                key={item.id}
                onClick={() => onCategoryChange(item)}
                className={`transition-colors ${
                  currentCategory?.id === item.id
                    ? 'text-blue-600'
                    : 'text-gray-600 hover:text-blue-600'
                }`}
              >
                {item.name}
              </button>
            ))}
          </nav>

          <div className="flex items-center gap-4">
            <div className="relative hidden sm:block">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
              <Input
                type="text"
                placeholder="搜索文章..."
                className="pl-10 w-64"
                value={searchInput}
                onChange={(e) => {
                  const value = e.target.value;
                  setSearchInput(value);
                  // 当搜索框清空时，自动搜索当前分类全部内容
                  if (value === '') {
                    onSearch('');
                  }
                }}
                onKeyPress={(e) => {
                  if (e.key === 'Enter') {
                    const value = e.currentTarget.value;
                    setSearchInput(value);
                    onSearch(value);
                  }
                }}
              />
            </div>
            <div className="flex items-center gap-3">
            {/* 桌面端显示用户信息 */}
            {isLoggedIn ? (
              <div className="hidden md:flex items-center gap-3">
                <span className="text-sm text-gray-600">
                  欢迎, {userEmail}
                </span>
                <div className="relative" ref={dropdownRef}>
                  <button
                    onClick={() => setIsDropdownOpen(!isDropdownOpen)}
                    className="relative flex items-center justify-center w-8 h-8 rounded-full overflow-hidden border-2 border-blue-100 hover:border-blue-300 transition-all duration-200 focus:outline-none"
                    aria-label="用户菜单"
                  >
                    <img
                      src={userAvatar}
                      alt="用户头像"
                      className="w-full h-full object-cover"
                      onError={(e) => {
                        const target = e.target as HTMLImageElement;
                        target.src = `https://ui-avatars.com/api/?name=${encodeURIComponent(userEmail.split('@')[0] || 'User')}&background=random`;
                      }}
                    />
                  </button>
                  {isDropdownOpen && (
                    <div className="absolute right-0 mt-2 w-48 bg-white rounded-md shadow-lg border border-gray-200 py-1 z-50 transition-all duration-200 scale-100 opacity-100">
                      <Link href="/profile"
                        onClick={handleProfileClick}
                        className="block w-full text-left px-4 py-2 text-sm text-gray-700 hover:bg-gray-100 flex items-center gap-2"
                      >
                        <User className="w-4 h-4" />
                        个人中心
                      </Link>
                      <button
                        onClick={() => {
                          setIsDropdownOpen(false);
                          handleLogout();
                        }}
                        className="block w-full text-left px-4 py-2 text-sm text-gray-700 hover:bg-gray-100 flex items-center gap-2"
                      >
                        <LogOut className="w-4 h-4" />
                        登出
                      </button>
                    </div>
                  )}
                </div>
              </div>
            ) : (
              <LoginRegisterModal onLoginSuccess={handleLoginSuccess} />
            )}

            {/* 移动端菜单按钮 */}
            <Button 
              variant="ghost" 
              size="icon" 
              className="md:hidden"
              onClick={() => setIsMobileMenuOpen(true)}
              ref={menuButtonRef}
            >
              <Menu className="w-5 h-5" />
            </Button>
            
            {/* 移动端弹出菜单 - 右上角样式 */}
            {isMobileMenuOpen && (
              <div className="fixed right-4 top-16 z-50 bg-white shadow-lg rounded-lg border border-gray-200 w-48 md:hidden transform transition-all duration-300 ease-out scale-100 opacity-100 translate-y-0" ref={menuRef} style={{animation: 'bounceIn 0.3s ease-out'}}>
                <div className="p-2">
                  {/* 移动端显示用户信息 */}
                  {isLoggedIn && (
                    <div className="px-3 py-2 text-sm text-gray-600 mb-2 border-b border-gray-100 flex items-center gap-2">
                      <div className="w-6 h-6 rounded-full overflow-hidden">
                        <img
                          src={userAvatar}
                          alt="用户头像"
                          className="w-full h-full object-cover"
                          onError={(e) => {
                            const target = e.target as HTMLImageElement;
                            target.src = `https://ui-avatars.com/api/?name=${encodeURIComponent(userEmail.split('@')[0] || 'User')}&background=random`;
                          }}
                        />
                      </div>
                      欢迎, {userEmail}
                    </div>
                  )}
                  
                  <button
                    onClick={() => {
                      onCategoryChange(null);
                      setIsMobileMenuOpen(false);
                    }}
                    className={`block w-full text-left px-3 py-2 rounded-md mb-1 transition-colors menu-item-hover ${currentCategory === null ? 'bg-blue-50 text-blue-600' : 'hover:bg-gray-100'}`}
                  >
                    全部
                  </button>
                  {categories.map((item) => (
                    <button
                      key={item.id}
                      onClick={() => {
                        onCategoryChange(item);
                        setIsMobileMenuOpen(false);
                      }}
                      className={`block w-full text-left px-3 py-2 rounded-md mb-1 transition-colors menu-item-hover ${currentCategory?.id === item.id ? 'bg-blue-50 text-blue-600' : 'hover:bg-gray-100'}`}
                    >
                      {item.name}
                    </button>
                  ))}
                  
                  {/* 移动端用户菜单 */}
                  {isLoggedIn && (
                    <>
                      <Link href="/profile"
                        onClick={() => {
                          handleProfileClick();
                          setIsMobileMenuOpen(false);
                        }}
                        className="block w-full text-left px-3 py-2 rounded-md text-gray-600 hover:bg-gray-100 menu-item-hover"
                      >
                        <span className="flex items-center gap-2">
                          <User className="w-4 h-4" />
                          个人中心
                        </span>
                      </Link>
                      <button
                        onClick={() => {
                          handleLogout();
                          setIsMobileMenuOpen(false);
                        }}
                        className="block w-full text-left px-3 py-2 rounded-md text-red-500 hover:bg-red-50 menu-item-hover"
                      >
                        <span className="flex items-center gap-2">
                          <LogOut className="w-4 h-4" />
                          登出
                        </span>
                      </button>
                    </>
                  )}
                </div>
              </div>
            )}
            {/* 手机端弹出菜单结束 */}

          </div>
          </div>
        </div>
      </div>
    </header>
  );
}
